package pl.th.permission.plugin.transform;

import com.android.build.api.transform.JarInput;
import com.android.build.api.transform.Status;
import com.android.build.api.transform.TransformInvocation;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;

public class ParallelTransformer extends SerialTransformer{

    private final ExecutorService mExecutor;
    private final Collection<Callable<Object>> mTasks;

    public ParallelTransformer(TransformInvocation invocation) {
        super(invocation);
        mExecutor = new ForkJoinPool();
        mTasks = new LinkedList<>();
    }

    @Override
    public void transform() throws Exception {
        super.transform();
        mExecutor.invokeAll(mTasks);
    }

    @Override
    protected void handleIncrementalDirInputFile(File srcFile, Status status, File srcDir, File destDir) {
        mTasks.add(() -> {
            super.handleIncrementalDirInputFile(srcFile, status, srcDir, destDir);
            return null;
        });
    }

    @Override
    protected void handleNotIncrementalDirInputFile(File srcFile, File srcDir, File destDir){
        mTasks.add(() -> {
            super.handleNotIncrementalDirInputFile(srcFile, srcDir, destDir);
            return null;
        });
    }

    @Override
    protected void handleCopiedJarInput(JarInput input){
        mTasks.add(() -> {
            super.handleCopiedJarInput(input);
            return null;
        });
    }

    @Override
    protected void handleRemovedJarInput(JarInput input){
        mTasks.add(() -> {
            super.handleRemovedJarInput(input);
            return null;
        });
    }
}
